package com.chunguang.netty;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.chunguang.netty.domain.RequestData;
import com.chunguang.netty.listener.ApplicationFactory;
import com.chunguang.netty.protol.ResponseData;
import com.chunguang.netty.service.RequestDataService;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

@Component
public class NettyServerHandler extends ChannelHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 
	}

	//@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		//获取请求数据对象
		RequestData requestData = (RequestData)msg;
		
		//通用类:ContextLoader
		ApplicationContext application = ApplicationFactory.getContext();
		RequestDataService service = (RequestDataService) application.getBean("datCheckDataDao");	
		
		//返回数据对象
		ResponseData responseData = new ResponseData();
		try {
			if(!service.exist(requestData.getCheckNumber())){
				service.insert(requestData);
			}
			else {
				service.update(requestData);
			}
			System.out.println("中心服务器端收到: " +  requestData.getCheckNumber());
			responseData.setCheckNo(requestData.getCheckNumber());
			responseData.setSuccess(true);
			responseData.setMessage("数据交换成功!");
			
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCheckNo(requestData.getCheckNumber());
			responseData.setSuccess(false);
			responseData.setMessage("数据交换失败!");
		}
		ctx.writeAndFlush(responseData);
	}

	//@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	 
	}

	
	
}
